//
//  UINavigationController.swift
//  
//
//  Created by tangbl93 on 2021/3/23.
//

import UIKit

public extension UINavigationController {
    
    /// pop to specify page
    func yx_popViewController(viewControllerClass classType: AnyClass, animated: Bool = true, completion: VoidClosure? = nil) {
        
        if viewControllers.count <= 1 { return }
        
        for viewController in viewControllers.reversed() where viewController.isKind(of: classType) {
            
            if let completion = completion {
                CATransaction.begin()
                CATransaction.setCompletionBlock(completion)
            }
            
            popToViewController(viewController, animated: animated)
            
            if let _ = completion {
                CATransaction.commit()
            }
            return
        }
    }
    
    /// pop specify times
    func yx_popViewController(count: Int, animated: Bool = true, completion: VoidClosure? = nil) {
        
        if viewControllers.count <= 1 || count <= 0 { return }
        
        let dismissCount: Int = count - 1
        for _ in 0..<dismissCount {
            popViewController(animated: false)
        }
        
        if let completion = completion {
            CATransaction.begin()
            CATransaction.setCompletionBlock(completion)
        }
        
        popViewController(animated: animated)
        
        if let _ = completion {
            CATransaction.commit()
        }
    }
}
